package com.cucn.ingmall.coupon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.cucn.ingmall.coupon.entity.SeckillSkuRelationEntity;
import com.cucn.ingmall.coupon.service.SeckillSkuRelationService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cucn.common.utils.PageUtils;
import com.cucn.common.utils.Query;

import com.cucn.ingmall.coupon.dao.SeckillSessionDao;
import com.cucn.ingmall.coupon.entity.SeckillSessionEntity;
import com.cucn.ingmall.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Resource
    private SeckillSessionDao seckillSessionDao;
    @Resource
    private SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLastThreeDays() {
        //计算最近三天的时间
        String startTime = startTime();
        String endTime = endTime();

        List<SeckillSessionEntity> session = seckillSessionDao.getLastThreeDays(startTime, endTime);

        if (CollectionUtil.isNotEmpty(session)) {
            session.forEach(seckillSession -> {
                List<SeckillSkuRelationEntity> sku = seckillSkuRelationService.getSkuBySessionId(seckillSession.getId());
                seckillSession.setSkuRelationList(sku);
            });
        }

        return session;
    }

    /**
     * 最近三天的起始时间
     */
    private String startTime() {
        LocalDateTime dateTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 最近三天的结束时间
     */
    private String endTime() {
        LocalDate now = LocalDate.now();
        LocalDateTime dateTime = LocalDateTime.of(now.plusDays(2L), LocalTime.MAX);

        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
}